package com.keter.config;

import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.keter.domains.MyClientUserDetails;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * Created by gulx@neusoft.com on 2020/6/8.
 */
public class ClientUserUtil {
    private static final Logger logger = LoggerFactory.getLogger(ClientUserUtil.class);
    private static ClientUserUtil  clientUserUtil = new ClientUserUtil();
    public static ClientUserUtil instance(){
        return clientUserUtil;
    }

    LoadingCache<String, MyClientUserDetails> cache = CacheBuilder.newBuilder()
            .maximumSize(1000)
            .expireAfterAccess(10, TimeUnit.SECONDS)
            .build(new CacheLoader<String, MyClientUserDetails>() {
                @Override
                public MyClientUserDetails load(String clientId) {
                    return retrieveClientDetailsFromDB(clientId);
                }
            });

    public MyClientUserDetails retrieveClientDetails(String clientId) {
        try {
            return cache.get(clientId);
        } catch (ExecutionException e) {
            logger.error("缓存执行失败！", e);
        }
        return retrieveClientDetailsFromDB(clientId);
    }

    private MyClientUserDetails retrieveClientDetailsFromDB(String clientId) {
        logger.info("---------- retrieve Client DetailService From DB! -----------");
        Record record = Db.findFirst("select * from oauth_client_details where client_id=?",clientId);
        Validate.notNull(record,"认证失败!");
        MyClientUserDetails clientDetails = new MyClientUserDetails(
                record.getStr("id"),
                clientId,
                record.getStr("resource_ids"),
                record.getStr("scope"),
                record.get("authorized_grant_types"),
                record.getStr("authorities"),
                record.getStr("web_server_redirect_uri")
        );
        if(Strings.isNullOrEmpty(record.getStr("client_secret"))){
            clientDetails.setClientSecret("");
        }
        else {
            clientDetails.setClientSecret(record.getStr("client_secret"));
        }
        return clientDetails;
    }
}

